﻿using Dapper;
using System;
using BCEntity.HelpDocument.HelpDocumentation;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;

namespace BCData.HelpDocument.HelpDocumentation
{
    /// <summary>
    /// 帮助
    /// </summary>
    public class HelpDocumentationData : IHelpDocumentationData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM helpdocumentation";
        private const string QUERY = @"SELECT HelpDocumentationId,UpdateTime,EditAdminId,EditAdminName,DocumentCode,HelpDocumentCategoryId,DocumentCategoryName,Title,Content,
                                            CreateTime,CreateAdminId,CreateAdminName 
                                        FROM helpdocumentation";
        public HelpDocumentationData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }
        #region 检查帮助是否存在
        public async Task<bool> Exists(long helpDocumentationId)
        {
            string sql = string.Format(@"{0} WHERE HelpDocumentationId=?HelpDocumentationId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?HelpDocumentationId", helpDocumentationId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<bool> Exists(string documentCode)
        {
            string sql = string.Format(@"{0} WHERE DocumentCode=?DocumentCode", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?DocumentCode", documentCode, DbType.AnsiString,size:100);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加帮助
        public async Task<HelpDocumentationEntity> Add(HelpDocumentationEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("helpdocumentation", new string[] { "DocumentCode", "HelpDocumentCategoryId", "DocumentCategoryName", "Title", "Content",
                "CreateAdminId", "CreateAdminName" });
            sql = string.Format("{0} {1} WHERE HelpDocumentationId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?UpdateTime", entity.UpdateTime, DbType.DateTime);
            parameters.Add("?DocumentCode", entity.DocumentCode?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?HelpDocumentCategoryId", entity.HelpDocumentCategoryId, DbType.Int64, size: 20);
            parameters.Add("?DocumentCategoryName", entity.DocumentCategoryName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?Title", entity.Title?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?Content", entity.Content, DbType.String);
            parameters.Add("?CreateAdminId", entity.CreateAdminId, DbType.Int64, size: 20);
            parameters.Add("?CreateAdminName", entity.CreateAdminName?.Trim(), DbType.AnsiString, size: 20);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<HelpDocumentationEntity>(sql, parameters, databaseContext.Transaction);

        }
        #endregion

        #region 修改帮助
        public async Task<HelpDocumentationEntity> Update(HelpDocumentationEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("helpdocumentation", new string[] { "UpdateTime", "EditAdminId", "EditAdminName", "DocumentCode", "HelpDocumentCategoryId",
                "DocumentCategoryName", "Title", "Content" }, new string[] { "HelpDocumentationId" });
            sql = string.Format("{0} {1} WHERE HelpDocumentationId=?HelpDocumentationId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?HelpDocumentationId", entity.HelpDocumentationId, DbType.Int64, size: 20);
            parameters.Add("?UpdateTime", DateTime.Now, DbType.DateTime);
            parameters.Add("?EditAdminId", entity.EditAdminId, DbType.Int64, size: 20);
            parameters.Add("?EditAdminName", entity.EditAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?DocumentCode", entity.DocumentCode?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?HelpDocumentCategoryId", entity.HelpDocumentCategoryId, DbType.Int64, size: 20);
            parameters.Add("?DocumentCategoryName", entity.DocumentCategoryName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?Title", entity.Title?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?Content", entity.Content, DbType.String);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<HelpDocumentationEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 删除帮助
        public async Task<bool> Delete(long helpDocumentationId)
        {
            string sql = @"DELETE FROM helpdocumentation WHERE HelpDocumentationId=?HelpDocumentationId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?HelpDocumentationId", helpDocumentationId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取帮助
        public async Task<HelpDocumentationEntity> GetEntity(long helpDocumentationId)
        {
            string sql = string.Format(@"{0} WHERE HelpDocumentationId=?HelpDocumentationId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?HelpDocumentationId", helpDocumentationId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<HelpDocumentationEntity>(sql, parameters);
        }
        public async Task<HelpDocumentationEntity> GetEntity(string documentCode)
        {
            string sql = string.Format(@"{0} WHERE DocumentCode=?DocumentCode", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?DocumentCode", documentCode, DbType.AnsiString, size: 100);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<HelpDocumentationEntity>(sql, parameters);
        }
        #endregion

        #region 获取帮助列表
        public async Task<IEnumerable<HelpDocumentationEntity>> GetList(long helpDocumentCategoryId)
        {
            string sql = string.Format(@"{0} WHERE HelpDocumentCategoryId=?HelpDocumentCategoryId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?HelpDocumentCategoryId", helpDocumentCategoryId, DbType.Int64);
            return await this.databaseContext.Slave.QueryAsync<HelpDocumentationEntity>(sql,parameters);
        }
        #endregion

        #region 获取帮助分页
        public async Task<(IEnumerable<HelpDocumentationEntity>, int)> Query(long? helpDocumentCategoryId,string searchKey, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (helpDocumentCategoryId.HasValue)
            {
                wheres.Add("HelpDocumentCategoryId=?HelpDocumentCategoryId");
                parameters.Add("?HelpDocumentCategoryId", helpDocumentCategoryId, DbType.Int64);
            }
            if (!string.IsNullOrWhiteSpace(searchKey))
            {
                wheres.Add("Title LIKE CONCAT('%',CONCAT(?Title,'%'))");
                parameters.Add("?Title", searchKey?.Trim(), DbType.AnsiString);
                wheres.Add("Content LIKE CONCAT('%',CONCAT(?Content,'%'))");
                parameters.Add("?Content", searchKey?.Trim(), DbType.AnsiString);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM helpdocumentation {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.Slave.QueryMultipleAsync<HelpDocumentationEntity, int>(sql, parameters);
        }
        #endregion
    }
}



